package protocol.control;

import exceptions.ArgumentException;
import protocol.Frame;

/**
 * A send request packet
 * @date 26.5.2011
 */
public class SendRequestPacket implements Frame {

	/**
	 * The requested filename
	 */
	private String filename;
	/**
	 * The opened port number for the file transfer
	 */
	private int port;
	
	public String getFilename() {
		return this.filename;
	}

	public void setFilename(String filename) throws ArgumentException {
		if (filename.length() > 255){
			throw new ArgumentException("Too long filename!");
		} else {
			this.filename = filename;
		}
	}

	public int getPort() {
		return this.port;
	}

	public void setPort(int port) throws ArgumentException {
		if (port >= 0 && port <= 65535) {
			this.port = port;
		} else {
			throw new ArgumentException("Invalid port number!");
		}
	}
	
	/**
	 * Constructor
	 */
	public SendRequestPacket() {	
	}
	
	/**
	 * Constructor
	 * @param bytes Supplied for the method parse()
	 */
	public SendRequestPacket(byte[] bytes) {
		this.parse(bytes);
	}

	/**
	 * The specified packet format is 
	 * | 255 bytes    | 2 bytes |
     * |--------------|---------|
	 * | Filename     | Port    |
	 * |--------------|---------|
	 * @return The packet as a byte array
	 */
	public byte[] build() {
		byte[] data = new byte[257];
		/**
		 * Set the filename to the packet
		 */
		System.arraycopy(
			this.getFilename().getBytes(), 0, // source
			data, 0, // destination
			this.getFilename().getBytes().length); // length
		/**
		 * Set the port number to the packet
		 */
		data[255] = (byte)(this.getPort() >> 8);
		data[256] = (byte)(this.getPort() & 0xFF);
		return data;
	}

	/**
	 * The specified packet format is 
	 * | 255 bytes    | 2 bytes |
     * |--------------|---------|
	 * | Filename     | Port    |
	 * |--------------|---------|
	 */
	public void parse(byte[] bytes) {
		byte[] filename = new byte[255];
		/**
		 * Read the filename
		 */
		System.arraycopy(
			bytes, 0, // source
			filename, 0, // destination
			255); // length
		try {
			/**
			 * Save the filename
			 */
			this.setFilename(new String(filename).trim());
			/**
			 * Save the port number
			 */
			this.setPort((((int)bytes[255] & 0xFF) << 8) | ((int)bytes[256] & 0xFF));
		} catch (ArgumentException e) {
			System.err.println(e.toString());
		}
	}

}